#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "voice.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    
    setFixedSize(size());
    watch = new Watch::Watch {QPoint{width()/2,wch_sz}};
    button = new Butt::Button {QPoint{width()/2,btn_pos},time};
    try {
        if (not clc_limit_mess.exists())
            throw File_not_found_error{};
        setWindowTitle(tr("停止在%1的秒表").arg(clc_limit.get_text()));
        Tm::Time task {clc_limit-voice_insep_count.imag()};
        for (int i{}; i!=voice_insep_count.real(); ++i) {
            task -= voice_insep_count.imag();
            sounds.append(QPair<Tm::Time,Voice_type>{task,Voice_type::insep});
        }
        for (int i{}; i!=voice_loose_count.real(); ++i) {
            task -= voice_loose_count.imag();
            sounds.append(QPair<Tm::Time,Voice_type>{task,Voice_type::loose});
        }
    }
    catch (Tm::Negative_error) {
        quit = tr("你时间设定得太短了，我都没时间播放声音了");
    }
    catch (File_not_found_error) {
        quit = tr("请勿删除时间设定文件");
    }
    connect(&timer, SIGNAL(timeout()), this, SLOT(frame_update()));
    timer.start(1000/frame_speed);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete watch;
    delete button;
}

void MainWindow::paintEvent(QPaintEvent* event)
{
    event->accept();
    QPainter pa {this};
    pa.drawPixmap(0, 0, snapshot);
}

void MainWindow::mousePressEvent(QMouseEvent* event)
{
    button->click(event->position());
}

void MainWindow::update_snapshot()
{
    QPixmap snap {size()};
    QPainter pa {&snap};
    pa.fillRect(QRect{QPoint{},size()}, wnd_back);
    QRect text_area {QPoint{},size()};
    pa.setFont(clc_font);
    pa.drawText(text_area, Qt::AlignCenter, time.get_text());
    pa.end();
    watch->draw(&snap);
    button->draw(&snap);
    snapshot = std::move(snap);
    update();
}

void MainWindow::frame_update()
{
    update_snapshot();
    if (not quit.isEmpty()) {
        QMessageBox::critical(this, tr("错误"), quit);
        qApp->exit(quit.length());
    }
    time.set_time();
    if (time>=clc_limit and time.running()) {
        Voice::beep(Voice_type::final);
        time = clc_limit;
        time.stop();
    }
    else if (not sounds.isEmpty() and time>=sounds.last().first) {
        Voice::beep(sounds.last().second);
        sounds.removeLast();
    }
}
